<?php
namespace App\Console\Commands;


use App\Api\Controllers\Config\EasyPayConfigController;
use App\Api\Controllers\Config\NewLandConfigController;
use App\Api\Controllers\Config\VbillConfigController;
use App\Api\Controllers\Vbill\PayController;
use App\Common\PaySuccessAction;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Store;
use App\Services\Pay\PayService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class VbillOrderSuccess extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'vbill_order_query';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新等待支付的订单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $time_start = date('Y-m-d 00:00:00', time());
        $time_end = date('Y-m-d H:i:s', time());
        Log::channel("vbill")->info("VbillOrderSuccess",[
            $time_start,
            $time_end
        ]);
        try{
            //等待支付订单信息
            $order_obj = DB::table('orders')
                ->select(['out_trade_no', 'trade_no' , 'qwx_no', 'other_no', 'store_id', 'ways_type', 'company', 'ways_type_desc', 'total_amount', 'rate', 'fee_amount', 'merchant_id', 'user_id', 'store_name', 'ways_source', 'device_id', 'pay_status'])
                ->whereIn('company', ['vbill', 'vbilla', 'newland', 'easypay'])
                ->where('pay_status', '2')
                ->where('created_at', '>=', $time_start)
                ->where('created_at', '<=', $time_end)
                ->get();

            if ($order_obj) {
                foreach ($order_obj as $key => $values) {
                    $store_obj = Store::where('store_id', $values->store_id)
                        ->select('config_id', 'merchant_id', 'pid')
                        ->first();
                    if (!$store_obj) {
                        continue;
                    }

                    $config_id = $store_obj->config_id;
                    $store_pid = $store_obj->pid;
                    $store_id = $values->store_id;
                    $ways_type = $values->ways_type;
                    $out_trade_no = $values->out_trade_no;
                    $pay_status = $values->pay_status;
                    $merchant_id = $values->merchant_id;

                    //随行付
                    if (12999 < $ways_type && $ways_type < 13999) {
                        $config = new VbillConfigController();
                        $vbill_config = $config->vbill_config($config_id);
                        if (!$vbill_config) {
                            continue;
                        }

                        $vbill_merchant = $config->vbill_merchant($store_id, $store_pid);
                        if (!$vbill_merchant) {
                            continue;
                        }

                        $obj = new PayController();
                        $data['request_url'] = $obj->order_query_url;
                        $data['mno'] = $vbill_merchant->mno;
                        $data['privateKey'] = $vbill_config->privateKey;
                        $data['sxfpublic'] = $vbill_config->sxfpublic;
                        $data['orgId'] = $vbill_config->orgId;
                        $data['out_trade_no'] = $out_trade_no;
                        $return = $obj->order_query($data);
//                        Log::info('随行付-定时任务查询等待支付-结果');
//                        Log::info($return);

                        //支付成功
                        if ($return['status'] == '1') {
                            $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['respData']['tranTime']));
                            $trade_no = $return['data']['respData']['sxfUuid'];
                            $buyer_pay_amount = $return['data']['respData']['totalOffstAmt'];
                            $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');

                            //改变数据库状态
                            if ($pay_status != '1') {
                                $insert_data = [
                                    'status' => '1',
                                    'pay_status' => '1',
                                    'pay_status_desc' => '支付成功',
                                    'buyer_logon_id' => '',
                                    'trade_no' => $trade_no,
                                    'pay_time' => $pay_time,
                                    'buyer_pay_amount' => $buyer_pay_amount,
                                ];
                                $this->update_day_order($insert_data, $out_trade_no);

                                //支付成功后的动作
//                                $data = [
//                                    'ways_type' => $ways_type,
//                                    'company' => $values->company,
//                                    'ways_type_desc' => $values->ways_type_desc,
//                                    'source_type' => '13000',
//                                    'source_desc' => '随行付',
//                                    'total_amount' => $values->total_amount,
//                                    'out_trade_no' => $out_trade_no,
//                                    'rate' => $values->rate,
//                                    'fee_amount' => $values->fee_amount,
//                                    'merchant_id' => $values->merchant_id,
//                                    'store_id' => $store_id,
//                                    'user_id' => $values->user_id,
//                                    'config_id' => $config_id,
//                                    'store_name' => $values->store_name,
//                                    'ways_source' => $values->ways_source,
//                                    'pay_time' => $pay_time,
//                                    'device_id' => isset($values->device_id) ? $values->device_id : '',
//                                ];
//                                PaySuccessAction::action($data);
                            }
                            else {
                                continue;
                            }
                        } //订单失败关闭
//                        elseif ($return['status'] == '3') {
//                            //改变数据库状态
//                            if ($pay_status != '1') {
//                                $insert_data = [
//                                    'status' => '3',
//                                    'pay_status' => '3',
//                                    'pay_status_desc' => '支付失败',
//                                ];
//                                $this->update_day_order($insert_data, $out_trade_no);
//                            }
//                            else {
//                                continue;
//                            }
//                        }
                        //其他
                        else {
                            continue;
                        }
                    }

                    //随行付a
                    if (18999 < $ways_type && $ways_type < 19999) {
                        $config = new VbillConfigController();
                        $vbilla_config = $config->vbilla_config($config_id);
                        if (!$vbilla_config) {
                            continue;
                        }

                        $vbilla_merchant = $config->vbilla_merchant($store_id, $store_pid);
                        if (!$vbilla_merchant) {
                            continue;
                        }

                        $obj = new PayController();
                        $data['request_url'] = $obj->order_query_url;
                        $data['mno'] = $vbilla_merchant->mno;
                        $data['privateKey'] = $vbilla_config->privateKey;
                        $data['sxfpublic'] = $vbilla_config->sxfpublic;
                        $data['orgId'] = $vbilla_config->orgId;
                        $data['out_trade_no'] = $out_trade_no;
                        $return = $obj->order_query($data);
//                        Log::info('随行付A-定时任务查询等待支付-结果');
//                        Log::info($return);

                        //支付成功
                        if ($return['status'] == '1') {
                            $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['respData']['tranTime']));
                            $trade_no = $return['data']['respData']['sxfUuid'];
                            $buyer_pay_amount = $return['data']['respData']['totalOffstAmt'];
                            $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');

                            //改变数据库状态
                            if ($pay_status != '1') {
                                $insert_data = [
                                    'status' => '1',
                                    'pay_status' => '1',
                                    'pay_status_desc' => '支付成功',
                                    'buyer_logon_id' => '',
                                    'trade_no' => $trade_no,
                                    'pay_time' => $pay_time,
                                    'buyer_pay_amount' => $buyer_pay_amount,
                                ];
                                $this->update_day_order($insert_data, $out_trade_no);
                            }
                            else {
                                continue;
                            }
                        } //订单失败关闭
//                        elseif ($return['status'] == '3') {
//                            //改变数据库状态
//                            if ($pay_status != '1') {
//                                $insert_data = [
//                                    'status' => '3',
//                                    'pay_status' => '3',
//                                    'pay_status_desc' => '支付失败',
//                                ];
//                                $this->update_day_order($insert_data, $out_trade_no);
//                            }
//                            else {
//                                continue;
//                            }
//                        }
                        //其他
                        else {
                            continue;
                        }
                    }

                    //新大陆
                    if (7999 < $ways_type && $ways_type < 8999) {
                        //读取配置
                        $config = new NewLandConfigController();
                        $new_land_config = $config->new_land_config($config_id);
                        if (!$new_land_config) {
                            continue;
                        }

                        $mybank_merchant = $config->new_land_merchant($store_id, $store_pid);
                        if (!$mybank_merchant) {
                            continue;
                        }

                        $request_data = [
                            'out_trade_no' => $out_trade_no,
                            'key' => $mybank_merchant->nl_key,
                            'org_no' => $new_land_config->org_no,
                            'merc_id' => $mybank_merchant->nl_mercId,
                            'trm_no' => $mybank_merchant->trmNo,
                            'op_sys' => '3',
                            'opr_id' => $merchant_id,
                            'trm_typ' => 'T',
                        ];
//                        Log::info('新大陆-轮询-交易查询');
//                        Log::info($request_data);
                        $obj = new \App\Api\Controllers\Newland\PayController();
                        $return = $obj->order_query($request_data);
//                        Log::info($return);

                        //支付成功
                        if ($return["status"] == 1) {
                            $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['sysTime']));
                            $trade_no = $return['data']['orderNo'];
                            $buyer_pay_amount = $return['data']['amount'] / 100;
                            $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');

                            //改变数据库状态
                            if ($pay_status != 1) {
                                $insert_data = [
                                    'status' => '1',
                                    'pay_status' => 1,
                                    'pay_status_desc' => '支付成功',
                                    'buyer_logon_id' => '',
                                    'trade_no' => $trade_no,
                                    'pay_time' => $pay_time,
                                    'buyer_pay_amount' => $buyer_pay_amount,
                                ];
                                $this->update_day_order($insert_data, $out_trade_no);
                            }
                        } else {
                            continue;
                        }
                    }

                    //易生支付
                    if (in_array($ways_type,[21001,21002,21004,61001,61002,61004])) {
                        //读取配置
                        $version="easypay";
                        if(in_array($ways_type,[61001,61002,61004])){
                            $version="easypaya";
                        }
                        //读取配置
                        $config = new EasyPayConfigController();
                        $easypay_config = $config->easypay_config($config_id);
                        if (!$easypay_config) {
                            continue;
                        }

                        $easypay_merchant = $config->easypay_merchant($store_id, $store_pid,$version);
                        if (!$easypay_merchant) {
                            continue;
                        }

                        $obj = new \App\Api\Controllers\EasyPay\PayController();
                        $easypay_data = [
                            'channel_id' => $easypay_config->channel_id, //渠道编号
                            'mer_id' => $easypay_merchant->termMercode, //终端商戶编号
                            'device_id' => $easypay_merchant->termTermcode, //终端编号
                            'out_trade_no' => $out_trade_no, //原交易流水
                            "private_key"=>$easypay_config->private_key
                        ];
//                        Log::info('易生支付-轮询-交易查询');
//                        Log::info($easypay_data);
                        $return = $obj->order_query($easypay_data); //-1 系统错误 0-其他 1-成功 2-下单失败
//                        Log::info($return);

                        //支付成功
                        if ($return['status'] == '1') {
                            $pay_time = $return['data']['wxtimeend'] ? date('Y-m-d H:i:s', strtotime($return['data']['wxtimeend'])): ''; //支付完成时间，如2009年12月27日9点10分10秒表示为20091227091010
                            $trade_no = $return['data']['wtorderid']; //系统订单号
                            $buyer_pay_amount = $return['data']['payamt'] ? ($return['data']['payamt']/100): ''; //实付金额，单位分
                            $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');

                            //改变数据库状态
                            if ($pay_status != 1) {
                                $insert_data = [
                                    'status' => '1',
                                    'pay_status' => 1,
                                    'pay_status_desc' => '支付成功',
                                    'buyer_logon_id' => '',
                                    'trade_no' => $trade_no,
                                    'pay_time' => $pay_time,
                                    'buyer_pay_amount' => $buyer_pay_amount,
                                ];
                                $this->update_day_order($insert_data, $out_trade_no);
                            }
                        }
                        //其他情况
                        else {
                            continue;
                        }
                    }

                }
            }
        } catch (\Exception $ex) {
            Log::info('等待支付状态轮询查询-错误');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }


    //当天交易公共更改
    public function update_day_order($update_data, $out_trade_no, $table = "")
    {
        try {
            if ($table == "") {
                $day = date('Ymd', time());
                $table = 'orders_' . $day;
            }

            if (Schema::hasTable($table)) {
                $order = DB::table($table)
                    ->where('out_trade_no', $out_trade_no)
                    ->update($update_data);
            } else {
                $order = Order::where('out_trade_no', $out_trade_no)
                    ->update($update_data);
            }

            //在这里新增逻辑-AMQP触发  处理-账单  处理-退款
            if(isset($update_data["status"])){
                $update_data["out_trade_no"]=$out_trade_no;
                if(in_array($update_data["status"],[1,'TRADE_SUCCESS', 'SUCCESS'])){
                    //这个是订单支付成功后触发
                    PayService::payOkHandle($update_data);
                }
//                if(in_array($update_data["status"],[6])){
//                    //这个是退款触发
//                    PayService::refundOkHandle($update_data);
//                }
            }

            if (Schema::hasTable('order_items')) {
                OrderItem::where('out_trade_no', $out_trade_no)->update($update_data);
            }

            return $order;
        } catch (\Exception $exception) {
            \Illuminate\Support\Facades\Log::info('update_order');
            \Illuminate\Support\Facades\Log::info($exception);
        }
    }


}
